import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from "sequelize";
import { DbDataSource } from './dbDataSource.model';
import { getPageData, getPageWhere } from '@/utils/page';
import { RESPONSE_CODE } from '@/enums/code';
import { GetDbDataSourcePageDto, AddDbDataSourceDto, UpdateDbDataSourceDto } from './dbDataSource.dto'

@Injectable()
export class DbDataSourceService {

  constructor(
    @InjectModel(DbDataSource)
    private dbDataSourceModel: typeof DbDataSource,

  ) { }

  /**
 * 获取数据库数据资源分页
 * @method get
 * @param 
 */
  async getDbDataSourcePage(getDbDataSourcePageDto: GetDbDataSourcePageDto) {
    const { dbName, connName, userCode, current, size } = getDbDataSourcePageDto

    let query = {};
    if (dbName) {
      query["dbName"] = { [Op.like]: `${dbName}%` };
    }
    if (connName) {
      query["connName"] = { [Op.like]: `${connName}%` };
    }
    if (userCode) {
      query["userCode"] = { [Op.like]: `${userCode}%` };
    }

    const { count, rows } = await this.dbDataSourceModel.findAndCountAll({
      where: query,
      ...getPageWhere(current, size)
    });

    return {
      code: RESPONSE_CODE.SUCCESS,
      data: getPageData(current, size, count, rows),
      msg: null,
    }
  }

  /**
   * 添加数据库数据资源
   * @method post
   * @param 
   */
  async addDbDataSource(addDbDataSourceDto: AddDbDataSourceDto) {
    const [created] = await this.dbDataSourceModel.findOrCreate({
      where: { connCode: addDbDataSourceDto.connCode },
      defaults: {
        ...addDbDataSourceDto,
      },
    });
    return {
      code: created ? RESPONSE_CODE.SUCCESS : RESPONSE_CODE.ERROR,
      data: null,
      msg: created ? null : '数据库数据源已存在',
    }
  }

  /**
   * 更新数据库数据资源
   * @method post
   * @param 
   */
  async updateDbDataSource(updateDbDataSourceDto: UpdateDbDataSourceDto) {
    await this.dbDataSourceModel.update({
      ...updateDbDataSourceDto
    }, {
      where: { connCode: updateDbDataSourceDto.connCode },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null,
    }
  }

  /**
   * 删除数据库数据资源
   * @method post
   * @param connCode
   */
  async deleteDbDataSource(connCode: string) {
    await this.dbDataSourceModel.destroy({
      where: { connCode },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null,
    }
  }

  /**
   * 获取数据库数据资源详情
   * @method get
   * @param connCode
   */
  async getDbDataSourceInfo(connCode: string) {
    const info = await this.dbDataSourceModel.findOne({
      where: { connCode },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: info,
      msg: null,
    }
  }
}
